//
//  UITextView+Extension.swift
//  EmoticonKeyboard
//
//  Created by 陈锦聪 on 16/4/2.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

extension UITextView {
    /// 插入表情
    func insertEmoticon(emoticon: CNEmoticonModel) {
        if let emoji = emoticon.emoji {
            insertText(emoji)
        }
        if let _ = emoticon.pngPath {
            let attrString = emoticon.emoticonModelToAttributedString(font!)
            let mutAttrString = NSMutableAttributedString(attributedString: attributedText)
            let selectRange = selectedRange
            mutAttrString.replaceCharactersInRange(selectRange, withAttributedString: attrString)
            attributedText = mutAttrString
            selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            // 主动调用代理&发送通知,隐藏提示文本
            delegate?.textViewDidChange?(self)
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
        }
    }
    /// 获取表情文本
    func emoticonsText() -> String {
        var result = ""
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            if let str = dict["NSAttachment"] as? CNTextAttachment {
                result += str.chs!
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                result += str
            }
        }
        return result
    }    
}
